package com.dx.mes.service.tool.service;


import com.dx.common.table.ppt.*;
import com.dx.mes.common.dao.IBisPmItemDao;
import com.dx.mes.common.dao.IRetToolPmDao;
import com.dx.mes.common.dao.IRetToolPmItemDao;
import com.dx.mes.common.dao.IRetToolStDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.tool.service.IMtppmitemService;
import com.dx.mes.facade.tool.tx.Mtppmitem.MtppmitemI;
import com.dx.mes.facade.tool.tx.Mtppmitem.MtppmitemIA;
import com.dx.mes.facade.tool.tx.Mtppmitem.MtppmitemO;
import com.dx.mes.facade.tool.tx.Mtppmitem.MtppmitemOA;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;


@Service("mtppmitemService")
public class MtppmitemService implements IMtppmitemService{
	private LogUtils logUtils;
	private static String TX_NAME = T_MTPPMITEM;

	@Autowired
	private IBisPmItemDao bisPmItemDao;
	@Autowired
	private IRetToolStDao retToolStDao;
	@Autowired
	private IRetToolPmItemDao retToolPmItemDao;
	@Autowired
	private IRetToolPmDao retToolPmDao;
	@Override
	public String subMainProc(String evt_no, String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(MtppmitemService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(MtppmitemService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");

		Session session = bisPmItemDao.getCrSession();
		long rtnCode = _NORMAL;
		String outMsg = null;

		MtppmitemI inTrx = new MtppmitemI();
		MtppmitemO outTrx = new MtppmitemO();
		outTrx.setTrx_id(TX_NAME);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		outTrx.setType_id(TRX_OUT);


		try {
			inTrx = JacksonUtil.fromJson(strInMsg, MtppmitemI.class);

			rtnCode = subMainProc2(inTrx, outTrx);
			if (rtnCode != _NORMAL) {
				TransactionAspectSupport.currentTransactionStatus()
						.setRollbackOnly();
				outTrx.setRtn_code(String.valueOf(rtnCode));
			} else {
				outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				session.flush();
			}
		} catch (Exception ex) {
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			logUtils.error(Util.stackTraceToString(ex));
		} finally {
			outMsg = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + outMsg + "]");
		}
		return outMsg;
	}

	private long subMainProc2(MtppmitemI inTrx, MtppmitemO outTrx) {
		long lRc = _NORMAL;
		char actionType = inTrx.getAction_flg().toCharArray()[0];
		switch (actionType) {
			case ACTION_FLG_QUERY: {
				lRc = queryByCondition(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case ACTION_FLG_NEW: {
				lRc = addORUpdateMItemFnc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'T': {
				lRc = queryPmTypeByToolIdOrModelFnc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'M': {
				lRc = queryPmItemFnc(inTrx, outTrx);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			default: {
				outTrx.setRtn_mesg("Invalide type input: [" + actionType + "]");
				return E_MTPPMITEM_INVALID_INPUT;
			}
		}
		return lRc;
	}
	
	/**
	 * 查询设备保养项目设定
	 * @param inTrx
	 * @param outTrx
	 * @return
	 */
	private long queryByCondition(MtppmitemI inTrx, MtppmitemO outTrx) {
		long lRc = _NORMAL;
		List<MtppmitemOA> oaryAList = new ArrayList<MtppmitemOA>();
		String tool_model = "";
		if(!Util.isSpaceCheck(inTrx.getTool_id())){
			//根据设备ID获取设备MODEL
			Ret_tool_st tool_st = retToolStDao.get(inTrx.getTool_id());
			if(tool_st==null){
				outTrx.setRtn_mesg("找不到设备[" + inTrx.getTool_id() + "]的信息[RET_TOOL_ST]");
				return E_RET_TOOL_ST + E_READ_NOT_FOUND;
			}if(Util.isSpaceCheck(tool_st.getTool_run_mode())){
				outTrx.setRtn_mesg("设备[" + inTrx.getTool_id() + "]未维护设备运行模式信息[RET_TOOL_ST]");
				return E_MTPPMITEM_NOT_FOUND_TOOL_MODE_SETTING;
			}else{
				tool_model = tool_st.getTool_run_mode();
			}
		}else if(!Util.isSpaceCheck(inTrx.getTool_model_fk())){
			tool_model = inTrx.getTool_model_fk();
		}
		
		String item_hql = "FROM Bis_pm_item where 1=1";
		if(!Util.isSpaceCheck(tool_model)){
			item_hql = item_hql + " and tool_model_fk='" + tool_model + "'";
		}
		
		if(!Util.isSpaceCheck(inTrx.getPm_type())){
			item_hql = item_hql + " and pm_type_fk='" + inTrx.getPm_type() + "'";
		}
		
		List<Bis_pm_item> bisPmItemList = bisPmItemDao.find(item_hql); 
		for(Bis_pm_item bis_pm_item : bisPmItemList ){
			MtppmitemOA oaryA = new MtppmitemOA();
			oaryA.setPm_type_fk(bis_pm_item.getId().getPm_type_fk());
			oaryA.setData_dsc(bis_pm_item.getId().getData_dsc());
			oaryA.setU_spec(bis_pm_item.getU_spec());
			oaryA.setL_spec(bis_pm_item.getL_spec());
			oaryA.setData_typ(bis_pm_item.getData_typ());
			oaryA.setData_cnt(bis_pm_item.getData_cnt());
			oaryA.setPm_note(bis_pm_item.getPm_note());
			oaryAList.add(oaryA);
		}
		
		outTrx.setOaryA(oaryAList);
		return lRc;
	}

	/**
	 * 新增或者修改保养项目
	 * @param inTrx
	 * @param outTrx
	 * @return
	 */
	public long addORUpdateMItemFnc(MtppmitemI inTrx, MtppmitemO outTrx){
		long lRc = _NORMAL;
		//检查该model对应的设备是否有设定计划，如果有不允许变更
/*		String sql_tool_pm="SELECT * FROM RET_TOOL_PM WHERE TOOL_ID_FK IN(" 
				+ "SELECT TOOL_ID FROM BIS_TOOL WHERE TOOL_MODEL='" + xpmlitemI.getTool_model_fk() 
				+ "') AND PM_STAT<>'COMP'";
		List<Object[]> objList  =  retToolPmDao.findBySQL(sql_tool_pm);
		if(objList.size()>0){
			xpmlitemO.setRtn_code(E_BIS_TOOL + E_READ_NOT_FOUND + "");
			xpmlitemO.setRtn_mesg("设备Model[" + xpmlitemI.getTool_model_fk()
					+ "]对应的设备还有未完成的PM计划，不允许修改！请先删除未完成的PM计划再修改！");
			return;
		}*/
		
		//先删除bis_pm_item表中所有记录
		String hql = "FROM Bis_pm_item where tool_model_fk ='"+ inTrx.getTool_model_fk() + "'";
		List<Bis_pm_item> bisPmItemList = bisPmItemDao.find(hql);
		if(!bisPmItemList.isEmpty()){
			try { 
				bisPmItemDao.deleteAll(bisPmItemList);
			} catch (Exception e) { 
				outTrx.setRtn_mesg(e.getCause().getMessage());
				return E_COMMON_ERROR_DELETE;
			}
		}

		//insert 重新insert
		List<MtppmitemIA> iaryAList = inTrx.getIaryA();
		List<Bis_pm_item> bis_pm_itemList = new ArrayList<Bis_pm_item>();
		for(MtppmitemIA iaryA:iaryAList){
			Bis_pm_itemId bis_pm_item_id = new Bis_pm_itemId();
			bis_pm_item_id.setTool_model_fk(inTrx.getTool_model_fk());
			bis_pm_item_id.setPm_type_fk(iaryA.getPm_type_fk());
			bis_pm_item_id.setData_dsc(iaryA.getData_dsc());
			
			Bis_pm_item bis_pm_item = new Bis_pm_item();
			bis_pm_item.setId(bis_pm_item_id);

            if(!Util.isSpaceCheck(iaryA.getU_spec())){
            	bis_pm_item.setU_spec(Double.valueOf(iaryA.getU_spec()));
            }
            if(!Util.isSpaceCheck(iaryA.getL_spec())){
            	bis_pm_item.setL_spec(Double.valueOf(iaryA.getL_spec()));	
            }
            if(!Util.isSpaceCheck(iaryA.getData_typ())){
            	bis_pm_item.setData_typ(iaryA.getData_typ());
            }
            if(!Util.isSpaceCheck(iaryA.getData_cnt())){
            	bis_pm_item.setData_cnt(Integer.valueOf(iaryA.getData_cnt()));
            }
            bis_pm_item.setPm_note(iaryA.getPm_note());
            bis_pm_item.setEvt_user(inTrx.getEvt_user());
            bis_pm_item.setEvt_timestamp(Util.getCurrentTimestamp());
            bis_pm_itemList.add(bis_pm_item);
		}
		
		try { 
			bisPmItemDao.saveOrUpdateAll(bis_pm_itemList);
		} catch (Exception e) { 
			outTrx.setRtn_mesg(e.getCause().getMessage());
			return E_COMMON_ERROR_UPDATE;
		}

		return lRc;
	}
	
	public long queryPmTypeByToolIdOrModelFnc(MtppmitemI inTrx, MtppmitemO outTrx){
		long lRc = _NORMAL;
		String tool_model = "";
		if(!Util.isSpaceCheck(inTrx.getTool_id())){
			//根据设备ID获取设备MODEL
			Ret_tool_st tool_st = retToolStDao.get(inTrx.getTool_id());
			if(tool_st==null){
				outTrx.setRtn_mesg("找不到设备[" + inTrx.getTool_id() + "]的信息[RET_TOOL_ST]");
				return E_RET_TOOL_ST + E_READ_NOT_FOUND;
			}if(Util.isSpaceCheck(tool_st.getTool_run_mode())){
				outTrx.setRtn_mesg("设备[" + inTrx.getTool_id() + "]未维护设备运行模式信息[RET_TOOL_ST]");
				return E_MTPPMITEM_NOT_FOUND_TOOL_MODE_SETTING;
			}else{
				tool_model = tool_st.getTool_run_mode();
			}
		}else if(!Util.isSpaceCheck(inTrx.getTool_model_fk())){
			tool_model = inTrx.getTool_model_fk();
		}else{
			outTrx.setRtn_mesg("设备代码、Model至少输入一种！");
			return E_MTPPMITEM_INVALID_INPUT; 
		}

		List<MtppmitemOA> oaryAList = new ArrayList<MtppmitemOA>();
		
		String pm_type_sql = "SELECT A.PM_TYPE_FK,B.EXT_1,B.DATA_DESC FROM " 
				+ "(SELECT DISTINCT PM_TYPE_FK FROM bis_pm_item WHERE TOOL_MODEL_FK in('" +  tool_model.replace(",", "','") + "')) A "
				+ "LEFT JOIN "
				+ "(SELECT EXT_1,DATA_DESC FROM bis_data WHERE DATA_CATE='PMTP') B "
				+ "ON A.PM_TYPE_FK=B.EXT_1";
		List<Object[]> objList  =  bisPmItemDao.findBySQL(pm_type_sql);
		if(objList.size()>0){
			for(int i=0; i<objList.size(); i++){
				Object[] obj = objList.get(i);
				if(obj[1] == null){
					outTrx.setRtn_mesg("找不到保养类型[" + obj[0].toString() + "]的参数设定");
					return E_MTPPMITEM_NOT_FOUND_PM_TYP_SETTING;
				}else if(obj[2] == null){
					outTrx.setRtn_mesg("找不到保养类型[" + obj[0].toString() + "]的类型描述");
					return E_MTPPMITEM_NOT_FOUND_PM_TYP_DSC;
				}
				MtppmitemOA oaryA = new MtppmitemOA();
				oaryA.setPm_type_fk(obj[1].toString());
				oaryA.setPm_type_dsc(obj[2].toString());
				oaryAList.add(oaryA);
			}
		}
		outTrx.setTool_model(tool_model);
		outTrx.setOaryA(oaryAList);
		return lRc;
	}
	private long queryPmItemFnc(MtppmitemI inTrx, MtppmitemO outTrx) {
		long lRc = _NORMAL;
		List<MtppmitemOA> oaryAList = new ArrayList<MtppmitemOA>();
		String evt_seq_id = inTrx.getEvt_seq_id();
		Ret_tool_pm ret_tool_pm = retToolPmDao.get(evt_seq_id);
		if(ret_tool_pm!=null&&PROC_IN_PROCESS.equals(ret_tool_pm.getPm_stat())){
			String hql ="FROM Ret_tool_pm_item where pm_item_id_fk='" + ret_tool_pm.getPm_item_id() + "'";
			List<Ret_tool_pm_item> ret_tool_pm_itemList = retToolPmItemDao.find(hql);
			if(ret_tool_pm_itemList.size()>0){
				for(Ret_tool_pm_item ret_tool_pm_item:ret_tool_pm_itemList){
					for(int i=0; i<ret_tool_pm_item.getData_cnt(); i++){
						MtppmitemOA oaryA = new MtppmitemOA();
						oaryA.setData_dsc("("+ (i+1) + " of "+ ret_tool_pm_item.getData_cnt() +") " + ret_tool_pm_item.getData_dsc());
						oaryA.setU_spec(ret_tool_pm_item.getU_spec());
						oaryA.setL_spec(ret_tool_pm_item.getL_spec());
						oaryAList.add(oaryA);
					}
				}
			}
		}
		outTrx.setOaryA(oaryAList);
		return lRc;
	}

}
